package thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * tryLock测试
 *
 * @author liweimin
 * @date 2021/5/7 15:26
 * @since
 */
public class Test04 {
    public static void main(String[] args) {
        Timelock timelock = new Timelock();

        new Thread(timelock).start();
        new Thread(timelock).start();
    }

    static class Timelock implements Runnable {

        private static ReentrantLock lock = new ReentrantLock();

        @Override
        public void run() {
            try {
                if (lock.tryLock(1, TimeUnit.SECONDS)) {
                    System.out.println(Thread.currentThread().getName() + "获得锁，执行耗时任务");

                    TimeUnit.SECONDS.sleep(3);
                } else {//未获得锁
                    System.out.println(Thread.currentThread().getName() + "未获得锁");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }
}
